package com.caiwangdai.app.origin.list.decoration

import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View

/**
 * @project KotLinProject
 * @author 艹羊
 * @date 2017/6/16 上午10:29
 * @description
 */
class GridSpacingItemDecoration : RecyclerView.ItemDecoration {

    var spanCount: Int = 0//几列
    var spacing: Int = 0//列间距
    var includeEdge: Boolean = false

    constructor(spanCount: Int, spacing: Int, includeEdge: Boolean) : super() {
        this.spanCount = spanCount
        this.spacing = spacing
        this.includeEdge = includeEdge
    }

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        val position: Int = parent?.getChildAdapterPosition(view)!!
        val column: Int = position % spanCount//位于第几列
        if (includeEdge) {
            outRect?.left = spacing - column * spacing / spanCount
            outRect?.right = (column + 1) * spacing / spanCount
            if (position < spanCount)
                outRect?.top = spacing
            outRect?.bottom = spacing
        } else {
            outRect?.left = column * spacing / spanCount
            outRect?.right = spacing - (column + 1) * spacing / spanCount
            if (position < spanCount) {
                outRect?.top = spacing
            }
            outRect?.bottom = spacing
        }
    }
}